package cn.tedu.fresheveryday.service.impl;

import cn.tedu.fresheveryday.exception.ServiceException;
import cn.tedu.fresheveryday.mapper.OrderDistributionMapper;
import cn.tedu.fresheveryday.mapper.OrderMapper;
import cn.tedu.fresheveryday.pojo.entity.OrderDistribution;
import cn.tedu.fresheveryday.pojo.vo.OrderSimpleVO;
import cn.tedu.fresheveryday.restful.ResponseCode;
import cn.tedu.fresheveryday.service.IOderDistributionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class OrderDistributionServiceImpl implements IOderDistributionService {
    @Autowired
    OrderDistributionMapper mapper;

    @Autowired
    OrderMapper orderMapper;

    @Override
    public void insert(OrderDistribution distribution) {
        mapper.insert(distribution);
    }

    @Override
    public void updateById(OrderDistribution distribution) {
        // 通过配送信息id查询订单
        OrderSimpleVO order = orderMapper.selectByDistId(distribution.getId());

        // 查询结果为空，未查询到相关订单
        if (order == null) {
            throw new ServiceException(ResponseCode.BAD_REQUEST, "订单不存在");
        }
        // 订单修改次数大于0
        if (order.getUpdateTimes() > 0) {
            throw new ServiceException(ResponseCode.BAD_REQUEST, "修改失败，您的订单已修改过一次");
        }

        // 修改配送信息
        mapper.updateById(distribution);
        // 修改订单修改次数为1
        orderMapper.updateUpdateTimesById(order.getId(), 1);

    }

    @Override
    public OrderDistribution selectByOrderId(int orderId) {
        return mapper.selectByOrderId(orderId);
    }

}